import Vue from 'vue';
import {Util, MessageBox, VueBus} from '@lowcode/jpaas-common-lib';
import {Formula} from './FormulaUtil.js';
import FormMethods from './FormFunctions.js';
import _validVtype from './vtype.js';
import moment from "moment";
import FormConstant from './FormConstant.js';
import FormPcApi from './api/FormApi.js';
import rxSubDialog from "./common/rxSubDialog";
import {debounce} from "lodash-es";

import FormCalc from "./FormCalc";
import CustomQuery from "./CustomQuery";
import SubtableFunc from "./SubTableFunc";

import {I18Parse,CommonLang} from '@lowcode/jpaas-common-lib';
import jsCompsLang from '../../../../../locales/lang/impl/form/jsCompsLang';
let lang = jsCompsLang;
let i18n=function (langKey,text) {
    return I18Parse.getI18Val(lang.jsCompsLang,langKey, text)
}


Vue.use(VueBus);

var FormulaUtil = Formula;

export default {
    data() {
        return {
            html: "",
            script: "",
            item: {},
            subName: "",
            rowIndex: "",
            alias: "",
            idField: "ID_",
            instId: "",
            defId: "",
            //表单上下文数据。
            opinionSetting: [], //审批意见配置
            opinionHistorys: [], //审批意见历史
            opinionData: {}, //审批意见数据,
            calcVal: {},
            fromTabActive: 'tab0',
            blockActive: null,
            mainUniqueList: [],//唯一字段
            formDesigner: false,
            formDesignerAlias: "",
            required: {},
            readonly:false,
            subReadonly:false,
            //延迟处理
            timer:0,

            topVm:true,
            //权限
            permission:{},
            //上下文数据
            formContext:{},
            //主表查询完成
            iscompleteMain:false,
            curTree:{},
        }
    },
    created() {
        //初始化表单设定
        this.initFormSetting();
        //获取唯一字段
        this.initMainUniqueList();
        //初始数据。
        this.initDataFun("created");

    },
    mounted() {
        this.$nextTick(function () {
            this.initRequired();
            this.executeCustomQuery();
        })
    },
    methods: {
        //加入moment方法
        moment,
        ...FormMethods,
        ...SubtableFunc,
        ...Formula,
        /**
         * 没有主键，则获取父列表选择的左树信息，
         * 有主键，则更新左树信息到关联字段
         */
        getCurTree(){
            if(this.refKey){
                /**
                 * 主从分离，子表编辑数据初始化：
                 * 新增：绑定副键refKey
                 * 编辑：绑定副键refKey,设置表单数据editData
                 */
                this.$set(this.data, this.refKeyName, this.refKey);
            }else if(this.treeJson.listSearchType=='tree' && !this.pkId){
                this.curTree=this.$parent.getCurTree();
                //双值、单值计算
                if(this.treeJson.isSingle==0){
                    let colObj ={
                        label:this.curTree.name,
                        value:this.curTree.treeId
                    }
                    this.$set(this.data, this.treeJson.searchTreeColName, JSON.stringify(colObj));
                }else {
                    this.data[this.treeJson.searchTreeColName]=this.curTree.treeId;
                }
            }
        },
        //初始表单设定。
        initFormSetting(){
            var obj=this.formContext;
            if (obj) {
                this.instId = obj.instId;
                this.defId = obj.defId;
                this.opinionHistorys=obj.opinionHistorys;
            }
        },

        //获取唯一字段
        initMainUniqueList() {
            var meta=this.metadata;
            var ary = [];
            if (!meta || meta.length == 0) {
                return ;
            }

            for (var key in meta) {
                var json = meta[key];
                if (!json || !json.uniqueValue) {
                    continue;
                }
                ary.push(json.name);
            }
            this.mainUniqueList=ary;
        },

        initDataFun() {
            if (!this.data.initData) {
                this.$set(this.data, "initData", this.initData);
                if(this.iscompleteMain){
                    this.onload();
                }
                if(!this.pkId){
                    return;
                }
            }

            for (var key in this.data.initData) {
                var ary = this.data[FormConstant.SubPrefix + key];
                if(!ary || ary.length==0){
                    continue;
                }
                for (var i = 0; i < ary.length; i++) {
                    var o = ary[i];
                    this.$set(o, "index_", Util.randomId());
                    this.$set(o, "selected", false);
                }
            }
        },

        getPermission(tablename, fieldname) {
            try {
                if (tablename == 'main') {
                    return this.permission[fieldname];
                } else {
                    return this.permission[FormConstant.SubPrefix + tablename][fieldname];
                }
            } catch (e) {
                return 'r';
            }
        },
        getSubTablePermission(tablename, action) {
            try {
                return this.permission[FormConstant.SubPrefix + tablename].tablerights[action];
            } catch (e) {
                return 'r';
            }

        },
        getButtonPermission(alias) {
            try {
                return this.permission.buttons[alias];
            } catch (e) {
                return false;
            }
        },
        getAllTabPermission(ctlId) {
            var tabsData = this.metadata[ctlId].tabsData;
            var flag = false;
            for (var i = 0; i < tabsData.length; i++) {
                if (this.permission.tabs[ctlId][tabsData[i].name]) {
                    flag = true;
                }
            }
            return flag;
        },
        getTabPermission(ctlId, index) {
            try {
                var tabsData = this.metadata[ctlId].tabsData;
                var tab = tabsData[index];
                return this.permission.tabs[ctlId][tab.name];
            } catch (e) {
                return false;
            }
        },
        setReadonly(val) {
            this.readonly = val;
        },
        getReadonly() {
            return this.readonly;
        },
        getFormAlias() {
            return this.alias ? '_' + this.alias : this.alias;
        },
        getOpinionHistorys() {
            return this.opinionHistorys;
        },
        editSubOne(tablename, mode, tableLabel, idx,id) {
            let self_=this;
            var ary = self_.data[FormConstant.SubPrefix + tablename];
            let selecteds=[];
             ary.forEach(item => {
                if (item.selected) {
                    selecteds.push(item);
                }
            });
            if(selecteds.length==0 ||selecteds.length>1){
                self_.$message.error(self_.i18n('tip.editing','请选择一项需要的编辑项'));
                return;
            }
            let row =selecteds[0];
            let pkId = row[this.boRelations[tablename].fkMainId];
            function callBack(data) {
                var subTable = self_.data[FormConstant.SubPrefix + tablename];
                for(let i=0;i<subTable.length;i++){
                    let subData = subTable[i];
                    if(subData[self_.boRelations[tablename].fkMainId] === pkId){
                        Object.assign(subTable[i],data);
                        self_.$set(self_.data, FormConstant.SubPrefix + tablename,subTable);
                        break;
                    }
                }
                self_.$forceUpdate();
            }

            var conf = {
                component: this.components[tablename],
                title: this.i18n('form.formDialog','表单对话框'),
                curVm: this,
                max: true,
                data: {
                    pkId:pkId,
                    "refKey":this.data[this.boRelations[tablename].pkFieldName],
                    "refKeyName":this.boRelations[tablename].fkFieldName
                }
            };
            this.handleEdit(conf,callBack);
        },
        addSubOne(tablename, mode, tableLabel, idx,id) {
            let self_=this;
            function callBack(data) {
                var subTable = self_.data[FormConstant.SubPrefix + tablename];
                if(!subTable){
                    subTable=[];
                }
                data.index_ = Util.randomId();
                data.selected = false;
                subTable.push(data);
                self_.$set(self_.data, FormConstant.SubPrefix + tablename,subTable);
            }
            var conf = {
                component: this.components[tablename],
                title: this.i18n('form.formDialog','表单对话框'),
                curVm: this,
                max: true,
                data: {
                    "refKey":this.data[this.boRelations[tablename].pkFieldName],
                    "refKeyName":this.boRelations[tablename].fkFieldName
                }
            };
            this.handleEdit(conf,callBack);
        },
        handleEdit(conf,callBack){
            Util.open(conf, function (action,data) {
                if (action != 'ok'){
                    return;
                }
                if(callBack){
                    callBack(data);
                }
            });
        },
        add(tablename, mode, tableLabel, idx,id) {
            let row = Util.deepClone(this.data.initData[tablename]);
            row.index_ = Util.randomId();
            row.selected = false;

            var subTable = this.data[FormConstant.SubPrefix + tablename];
            if(!subTable){
                subTable=[];
                this.$set(this.data, FormConstant.SubPrefix + tablename,subTable);
            }
            if (this.beforeAdd) {
                var rtn=this.beforeAdd(tablename, row);
                if(rtn && !rtn.success){
                    this.$message.warning(rtn.msg);
                    return;
                }
            }

            if (mode == 'window') {
                let self_ = this;
                this.editRow(row, tablename, self_.$ti18('rxList.add','新增'), tableLabel, function (action, forminst) {
                    if (action == 'ok') {
                        subTable.push(forminst.item);
                        self_.$forceUpdate()
                    }
                },id)
            } else if (mode == "block") {
                var _i = idx + 1;
                if (idx == 0) {
                    if (subTable.length > 0) {
                        subTable.splice(_i, 0, row);
                    } else {
                        subTable.push(row);
                    }
                } else {
                    subTable.splice(_i, 0, row)
                }

            } else {
                subTable.push(row);
            }
        },
        addSub(tablename, mode, tableLabel) {
            let row = Util.deepClone(this.data.initData[tablename]);
            row.index_ = Util.randomId();
            row.selected = false;

            var ary = this.data[FormConstant.SubPrefix + tablename];
            if (!ary || ary.length == 0) return;
            var rows = ary.filter(item => item.selected);
            if (!rows || rows.length == 0) {
                this.$message.warning(this.$ti18("rxMsa.masWarn.selectOneRecord","请选择一行记录!"));
                return;
            }
            var selectedRow = rows[0];
            var subTable = this.data[FormConstant.SubPrefix + tablename];
            //设置父ID
            row.pid_ = selectedRow.index_;

            if (this.beforeAdd) {
                var rtn=this.beforeAdd(tablename, row);
                if(rtn && !rtn.success){
                    this.$message.warning(rtn.msg);
                    return;
                }
            }

            if (mode == 'window') {
                let self_ = this;
                this.editRow(row, tablename, self_.i18n('tip.addSub','新增子级'), tableLabel, function (action, forminst) {
                    if (action == 'ok') {
                        self_.data[FormConstant.SubPrefix + tablename].push(forminst.item);
                        self_.$forceUpdate()
                    }
                })
            } else {
                this.data[FormConstant.SubPrefix + tablename].push(row);
            }
        },
        editSub(row, tablename, type, tableLabel,id){
            function callBack(data) {
            }
            this.editRow(row, tablename, type, tableLabel,callBack,id);
        },
        editRow(row, tablename, type, tableLabel, call,id) {
            let div = document.createElement("div");
            div.innerHTML = this.html;
            let subDialog = div.querySelector("[id=dialog_" + tablename + "]");
            if (!subDialog) {
                this.$message.warning(this.i18n('tip.error','子表出错了'));
                return;
            }
            subDialog.removeAttribute("v-if");
            subDialog.removeAttribute("style");
            var html = subDialog.outerHTML;
            //更新自定义函数
            if (this.func_updBefore) {
                var rtn=this.func_updBefore(tablename, row);
                if(rtn && !rtn.success){
                    this.$message.warning(rtn.msg);
                    return;
                }
            }

            var conf = {
                component: rxSubDialog,
                data: {
                    html: html,
                    script: this.script,
                    data: {
                        data: this.data,
                        permission: this.permission,
                        alias:this.alias,
                        idField:this.idField,
                        metadata:this.metadata[id]
                    },
                    item: row,
                    subName: tablename,
                    mainAlias: this.alias
                },
                curVm: this,
                widthHeight: ['800px', '600px'],
                title: tableLabel + '-' + type
            }
            Util.open(conf, function (action) {
                call(action, this);
            });
        },
        edit(tablename, mode, tableLabel,idx,id) {
            var ary = this.data[FormConstant.SubPrefix + tablename];
            if (!ary || ary.length == 0) return;
            var rows = ary.filter(item => item.selected);
            if (!rows || rows.length == 0) return;
            var row = rows[0];
            if (!row.uid_) {
                row.uid_ = Util.randomId();
            }
            let self_ = this;
            this.editRow(row, tablename, self_.i18n('form.modify','修改'), tableLabel, function (action, forminst) {
                if (action == 'ok') {
                    for (let i = 0, j = ary.length; i < j; i++) {
                        if (ary[i].uid_ == forminst.item.uid_) {
                            Object.assign(ary[i],forminst.item);
                            break;
                        }
                    }
                    self_.$forceUpdate();
                }
            },id)
        },

        blockItemActive(idx) {
            if (this.blockActive == idx) {
                this.blockActive = null;
            } else {
                this.blockActive = idx;
            }
        },

        //子表自定义方法 方法名、表名
        customMethod(method, tablename) {
            var call = "this.func_" + method + "('" + tablename + "')";
            eval(call);
        },

        handleName(rule) {
            let _rule = rule;
            if (!_rule) return true;
            let func=new Function(_rule);
            func.bind(this);
            let rtn=func();
            return rtn;
        },
        conditionRight(_right, id, rule) {
            //条件设置 方法；
            if (!id) return true;
            if (!rule) return true;

            //计算子表
            if (_right == 'hidden') {
                //选择隐藏
                let flag = this.handleName(rule);
                //一直遍历rule 返回true则隐藏
                return !flag;
            }
            if (_right == "required") {
                var _html = this.html;
                if (_html) {
                    var _div = document.createElement('div');
                    _div.innerHTML = _html;
                    var _trs = _div.querySelectorAll('tr[id]');
                    for (let i = 0; i < _trs.length; i++) {
                        var _id = _trs[i].getAttribute('id');
                        if (_id == id) {//找到当前选中id的dom；
                            var _require = _trs[i].querySelectorAll('[verifyhide]');
                            if (_require && _require.length != 0) {
                                for (let n = 0; n < _require.length; n++) {
                                    var _name = _require[n].getAttribute('verifyhide');
                                    let _isRequire = this.handleName(rule);
                                    this.setRequired("main", _name, _isRequire);
                                    var _tdParent = _require[n].parentNode;
                                    var _tdPrev = _tdParent.previousElementSibling;
                                    if (_tdPrev) {
                                        _isRequire ? _tdPrev.className = 'required' : _tdPrev.className = '';
                                        //满足条件 必填；
                                        _tdPrev.setAttribute('class', 'required');
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }

        },
        conditionHidden(id, right, rule) {
            var _right = right || "hidden";
            return this.conditionRight(_right, id, rule);
        },
        conditionsHide(id, formula, state) {
            /*条件容器方法：
            * id：条件容器的id
            * formula：条件容器的公式
            * state：条件容器默认显示（display）或者隐藏(hide);
            * */
            if (formula) {
                let mainData = this.data;
                var _formula = ''
                var mainReg = /\{(\(.*?\)){0,1}(\w*?)\}/g;
                _formula = formula.replace(mainReg, function (a, b, c) {
                    return "mainData." + c + "";
                });
                let flag = eval(_formula);
                return state == "display" ? !flag : flag;
            } else {
                if (state) {
                    return state == "display" ? true : false;
                } else {
                    return true
                }

            }
        },
        async validMainUnique() {
            if (this.mainUniqueList && this.mainUniqueList.length > 0) {
                if ((!this.formDesigner && !this.alias) || (this.formDesigner && !this.formDesignerAlias)) {
                    return {
                        success: true
                    }
                }

                for (var i = 0; i < this.mainUniqueList.length; i++) {
                    var key = this.mainUniqueList[i];
                    var formJson = {
                        "alias": this.alias,
                        "keyName": key,
                        "keyValue": this.data[key]
                    }
                    if (this.formDesigner) {
                        formJson.alias = this.formDesignerAlias;
                    }
                    if (this.data[this.idField]) {
                        formJson.pk = this.data[this.idField];
                    }
                    var res = await FormPcApi.checkUniqueValue(formJson);
                    if (!res) {
                        return {
                            success: false,
                            msg: this.$rxComi18('mainTable','主表')+"【" + key + "】"+i18n('form.failed','唯一性校验不通过！')
                        }
                    }
                }
            }
            return {
                success: true
            }
        },
        validHtmls(field) {
            var isDom = false;
            var _dom = '';
            for (var id in this.metadata) {
                var _name = this.metadata[id].name;
                if (_name && _name == field) {
                    var id_dom = this.$el.querySelector('#' + id);
                    if (id_dom) {
                        isDom = true;
                        _dom = id_dom;
                        break;
                    }
                }
            }
            return isDom;
        },
        /**
         * 验证数据合法性。
         * 1.验证必填
         * 2.验证规则
         * @param validRequired
         * @param validType
         * @returns {{msg: string, success: boolean}|{success: boolean}|{msg: *, success: boolean}|{success: boolean}}
         */
        valid(validRequired, validType) {
            //获取所有要必填验证的字段；
            for (var field in this.data) {
                //验证主表：
                if (!field.startsWith(FormConstant.SubPrefix)) {
                    //遍历当前字段所对应的控件是不是在 表单里面显示(有可能隐藏掉了,隐藏了就不验证) ;
                    var isDom = this.validHtmls(field);
                    if (!isDom) {
                        continue;
                    }
                    var val = this.data[field];
                    var res = this._validReqVtp("main", field, val, validRequired, validType);

                    if (!res.success) {
                        return res
                    }
                } else {
                    var tableName = field.replace(FormConstant.SubPrefix, ""); //去除sub__前缀
                    //校验子表行数
                    var subData = this.data[field];
                    if (validRequired) {
                        var res = this._validRequired(tableName, "", subData);
                        if (!res.success) {
                            return res
                        }
                    }
                    //校验子表字段;
                    //一对多(子表)
                    if (subData instanceof Array) {
                        if (subData && subData.length > 0) {
                            var tableName = field.replace(FormConstant.SubPrefix, ""); //去除sub__前缀
                            var subObj = this.data.initData[tableName]
                            for (var subField in subObj) {
                                for (var i = 0, j = subData.length; i < j; i++) {
                                    var val = subData[i][subField];
                                    var res = this._validReqVtp(tableName, subField, val, validRequired, validType);
                                    if (!res.success) {
                                        return res
                                    }
                                }
                            }
                        }
                    } else {
                        //一对一子表 ；
                        var onetooneObj = this.data[field];
                        var onetooneName = field.replace(FormConstant.SubPrefix, ""); //去除sub__前缀
                        if (onetooneObj && onetooneObj != {}) {
                            for (var val in onetooneObj) {
                                var fieldVal = onetooneObj[val];
                                var res = this._validReqVtp(onetooneName, val, fieldVal, validRequired, validType);
                                if (!res.success) {
                                    return res
                                }
                            }
                        }
                    }


                }
            }
            return {
                success: true
            }
        },
        isNull(val) {
            if (val === 0) {
                return false;
            }
            if (val == '' || val == undefined || val == 'undefined' || val == '[]') {
                return true;
            }
            return false;
        },
        tableBlur(entName, index, field, record, blur) {
            if (blur) {
                var text = record[field];
                try {
                    if (text) {
                        text = eval("(" + record[field] + ")");
                        if (text instanceof Object) {
                            text = {key: record[field], label: text.label};
                        }
                    } else {
                        text = {key: text, label: text};
                    }
                } catch (e) {
                }
                blur(index, field, text, record);
            }
            for (var i = 0; i < this.data[FormConstant.SubPrefix + entName].length; i++) {
                var row = this.data[FormConstant.SubPrefix + entName][i];
                if (row.index_ == record.index_) {
                    record.selected = row.selected;
                    Object.assign(row, record);
                    delete row.children;
                }
            }
        },
        validFunc(entName, field, item) {
            var val = "";
            if (item == undefined) { //取弹出框的值
                val = this.data[field];
            } else { //取行内的值
                val = item[field];
            }
            var _required = this.getRequired(entName, field);
            if (_required && _required.required) {
                var required = _required.required;
            }
            if (required) {
                if (entName == 'main') {
                    var oldVal = this.data[field] + '';
                    let val = ''
                    if (oldVal.indexOf('{') > -1) {
                        //有可能是双值的情况
                        val = JSON.parse(oldVal).value;
                    } else {
                        val = oldVal;
                    }
                    if (this.isNull(val)) {
                        return {
                            success: false,
                            msg: this.$rxComi18('required', '必填'),
                            required: true
                        }
                    }
                } else {
                    if (this.isNull(val)) {
                        return {
                            success: false,
                            msg: this.$rxComi18('required', '必填'),
                            required: true
                        }
                    }
                }

            }
            //校验vtype
            try {
                return this._validVtype(entName, field, val);
            } catch (e) {
                return {
                    success: true
                };
            }
            return {
                success: true
            };
        },
        _validReqVtp(tableName, field, val, validRequired, validType) {
            if (validRequired) {
                var res = this._validRequired(tableName, field, val);
                if (!res.success) {
                    return res
                }
            }
            //校验vtype
            if (validType) {
                try {
                    var res = this._validVtype(tableName, field, val);
                    if (!res.success) {
                        return res
                    }
                } catch (e) {

                }
            }
            return {
                success: true
            };
        },
        _validRequired(tableName, field, val) {

            var value = val;
            var obj = this.getRequired(tableName, field);
            var comment = obj.comment;
            var required = obj.required;
            var valmode = obj.valmode;
            if (required) {
                //多值情况
                if (valmode == 'double') {
                    if (!value || value == "") {
                        //没有选值的话 不进入eval,否则会报错
                        value = "";
                    } else {
                        value = eval("(" + value + ")").value;
                    }
                }//多值情况
                else if(valmode=="multi") {
                    if (!value || value == "") {
                        value = "";
                    } else {
                        var obj = JSON.parse(value);
                        for (var key in obj) {
                            if (this.isNull(obj[key])) {
                                if (key == "province" || key == "province_code") {
                                    comment+=this.i18n('form.province','省');
                                }else if(key == "city" || key == "city_code"){
                                    comment+=this.i18n('form.city','市');
                                }else if(key == "county" || key == "county_code"){
                                    comment+=this.i18n('form.county','(县/区)');
                                }else{
                                    comment+=this.i18n('form.address','详情地址');
                                }
                                value="";
                                break;
                            }
                        }
                    }
                }
                if (this.isNull(value)) {
                    return {
                        success: false,
                        msg: comment + this.$rxComi18('required', '必填'),
                    }
                }
            }
            return {
                success: true
            }
        },
        _validVtype(entName, field, v) {
            if (this.isNull(v)) {
                return {
                    success:true
                }
            }
            var entObj = this.validRules[entName];
            var fieldMsg = "";
            var fieldObj = {};
            if (entName == 'main') {
                fieldObj = entObj[field];
                fieldMsg = this.$rxComi18('mainTable','主表')+"[" + fieldObj.comment + "]:"
            } else {
                fieldObj = entObj['fields'][field];
                fieldMsg = this.$rxComi18('subtable','子表') + entName + ","+this.$comi18('listDef.field', '字段')+"[" + fieldObj.comment + "]:"
            }
            var vtype = fieldObj.vtype;
            if (!vtype) return {
                success: true
            };
            var aryRule = vtype.split(";");
            for (var i = 0; i < aryRule.length; i++) {
                var rule = aryRule[i];
                var aryTmp = rule.split(":");
                var pre = aryTmp[0];

                if (pre == 'length') {
                    var arg = aryTmp[1];

                    if (typeof v === "number") {//如果是数字 则比较大小
                        /*
                        * arg = "14,2"
                        * _len = 14
                        * _m = 2
                        * */
                        var _len = parseInt(arg);
                        var _maxVal = Math.pow(10, _len);
                        if(arg.indexOf(',')!=-1){
                            var ary=arg.split(',');
                            var _m = parseInt(ary[0])-parseInt(ary[1]);
                            _maxVal = Math.pow(10, _m);
                        }


                        if (v > _maxVal) {
                            var ary=arg.split(',');
                            return {
                                success: false,
                                msg: fieldMsg + this.i18n('tip.allowed','只允许输入长度为')+(ary[0]-ary[1])
                            };
                        }
                    } else {

                        if (v && (v.toString().length > parseInt(arg))) {
                            return {
                                success: false,
                                msg: fieldMsg +this.i18n('tip.allowed','只允许输入长度为')+arg
                            };
                        }
                    }

                } else if (pre == 'vtype') {
                    var rule = aryTmp[1];
                    if (!rule) return {
                        success: true
                    };
                    var ruleObj = window["rules"][rule];
                    var prompt = ruleObj.prompt;
                    var regular = new RegExp(ruleObj.regular, "ig");

                    if (!regular.test(v)) {
                        return {
                            success: false,
                            msg: fieldMsg + prompt
                        };
                    }
                }
            }
            return {
                success: true
            };
        },
        initRequired() {
            var validRules = this.validRules;
            if (Object.keys(validRules).length < 1) { return; }
            for (let key in validRules) {
                if (key == "main") {
                    this.$set(this.required, key, {});
                    for (let item in validRules[key]) {
                        this.$set(this.required[key], item, validRules[key][item].required);
                    }
                } else {
                    this.$set(this.required, key, {fields: {}});
                    for (let item in validRules[key]) {
                        if (item == "required") {
                            this.$set(this.required[key], item, validRules[key][item]);
                        }
                        if (item == "fields") {
                            for (let m in validRules[key][item]) {
                                this.$set(this.required[key][item], m, validRules[key][item][m].required);
                            }
                        }
                    }
                }
            }
        },
        setRequired(entName, field, required) {
            var validRules = this.validRules;
            var tableObj = validRules[entName];
            var formObj = this.required[entName];
            if (entName == 'main') {
                tableObj[field].required = required;
                //主表字段必填
                formObj[field] = required;
            } else if (!field) {
                tableObj.required = required;
                //子表必填
                formObj.required = required;
            } else {
                tableObj['fields'][field].required = required;
                //子表里面的某个字段必填；
                formObj['fields'][field] = required;
            }
        },
        /**
         *
         * @param entName
         * @param field
         * @returns {{comment: *, required: *, valmode: *}|{required: boolean}}
         */
        getRequired(entName, field) {
            var required = false;
            var comment = "";
            var valmode = "";
            try {
                var validRules = this.validRules;
                if (Object.keys(validRules).length <= 0) {
                    return;
                }
                var tableObj = validRules[entName];
                if (entName == 'main') {
                    if (this.permission[field] == "required") {
                        this.$set(this.required[entName], field, true);
                        required = true;
                    } else {
                        required = tableObj[field].required;
                        this.$set(this.required[entName], field, required);
                    }
                    comment = this.$rxComi18('mainTable','主表') + tableObj[field].comment;
                    valmode = tableObj[field].valmode
                } else if (!field) { //子表必填
                    //判断当前字段的dom是不是有渲染出来(有可能通过条件设置什么的隐藏掉了)
                    // start
                    let dom = this.$el.querySelectorAll('[tabname]');
                    let isTable = false;
                    for (let i = 0; i < dom.length; i++) {
                        var _tabel = dom[i].getAttribute('tabname');
                        if (entName == _tabel) {
                            isTable = true;//如果dom没有隐藏
                            break;
                        }
                    }
                    //ent
                    if (isTable) {
                        required = tableObj.required;
                        comment = this.$rxComi18('subtable','子表') + tableObj.comment;
                    } else {
                        required = false;
                        comment = this.$rxComi18('subtable','子表') + tableObj.comment;
                    }

                } else {
                    var table=this.$el.querySelectorAll('[tabname=' + entName + ']')[0];
                    var tabletype=table.getAttribute("tabletype");
                    var tableFields=table.querySelectorAll('th[key='+field+']');
                    if(tabletype=='default' || tableFields.length>0) {
                        if (this.permission[FormConstant.SubPrefix + entName][field] == "required") {
                            required = true;
                            this.$set(this.required[entName], 'required', true);
                        } else {
                            required = tableObj['fields'][field].required;
                            this.$set(this.required[entName]['fields'], field, required);
                        }
                    }
                    comment = this.$rxComi18('subtable','子表')+"(" + entName + ")"+this.$comi18('listDef.field', '字段') + tableObj['fields'][field].comment;
                    valmode = tableObj['fields'][field].valmode;
                }

            } catch (e) {
                return {
                    required: false
                };
            }
            return {
                required: required,
                comment: comment,
                valmode: valmode
            };
        },
        executeCustomQuery() {
            var customQuery = this.customquery;
            if (!customQuery || JSON.stringify(customQuery) == '{}') return;
            var ID_ = this.data.ID_;
            var event = "";
            if (this.readonly) {
                event = "detailinit";
            } else {
                if (ID_) {
                    event = "editinit";
                } else {
                    event = "addinit";
                }
            }
            for (var key in customQuery) {
                if (key == "main") continue;
                var subQuery = customQuery[key];
                var subData = this.data[FormConstant.SubPrefix + key];
                if (!subData) continue;
                for (var subField in subQuery) {
                    var subFieldQuery = subQuery[subField];
                    for (var i = 0, j = subData.length; i < j; i++) {
                        var row = subData[i];
                        CustomQuery.excuteQuery(subFieldQuery, event, row, this);
                    }
                }
            }
            //计算主表 自定义查询
            var mainQuery = customQuery.main;
            if (mainQuery) {
                for (var mainField in mainQuery) {
                    var mainFieldQuery = mainQuery[mainField];
                    CustomQuery.excuteQuery(mainFieldQuery, event, {}, this);
                }
            }
        },
        valuechange(entName, field, row) {
            var customquery = this.customquery;
            try {
                var customqueryAry = customquery[entName][field];
                CustomQuery.excuteQuery(customqueryAry, "valuechange", row, this);
            } catch (e) {

            }
        },
        getCalcVal(id) {
            return this.calcVal[id]
        },
        getSubField(field, item) {
            if (!item) return '';
            var val = item[field];
            if (!val) return '';
            try {
                var obj = JSON.parse(val);
                if (typeof obj == 'object') {
                    return obj.label;
                }
            } catch (e) {
                //TODO handle the exception
                return val;
            }
            return val;
        },
        changeTab(activeKey) {
            //tab切換時調用事件（注意：不是控件tab容器）
            this.fromTabActive = activeKey;
        },
        tabPrev(idx, len) {
            //多tab上一步验证；
            if (idx == 0) {
                this.$message.warning("亲~现在已经是第一个了呢。")
                return;
            }
            let _i = idx - 1;
            this.fromTabActive = 'tab' + _i;

        },
        tabNext(idx, len) {
            //多tab下一步验证；
            let _i = idx + 1;
            if (_i == len) {
                this.$message.warning("亲~当前已经是最后一个了喔。");
                return;
            }
            let _fromTab = this.$refs.fromTab;
            let sub_tab = _fromTab.$el.querySelector('#fromTab' + idx);
            let _template = sub_tab.querySelectorAll('[tabname]');
            for (let i = 0; i < _template.length; i++) {
                let _dom = _template[i];
                let _cls = _dom.getAttribute("class");
                let _name = _dom.getAttribute('tabname');
                let _type = _dom.getAttribute('type');
                let _ctltype = _dom.getAttribute('ctltype');
                //如果控件是必填  没有填值的时候 会挂载一个 requireds的类名 所以 判断该控件有没有requireds；
                if (_cls.includes('requireds') && _type == "main") {
                    MessageBox.show({
                        message: "【" + _name + "】是必填项",
                        data: ''
                    })

                    return;
                }

                if (_ctltype == 'rx-table') {
                    //找到子表的tableEmpty 如果有数据的话  是没有class = "tableEmpty"节点的；
                    let _tableEmpty = _dom.getElementsByClassName('tableEmpty')[0];
                    //子表本身 必填 req="yes"
                    let _req = _dom.getAttribute('req');
                    if (_tableEmpty && _req == "yes") {
                        MessageBox.show({
                            message: "【" + _name + "】"+this.i18n('form.required','是必填项'),
                            data: ''
                        })
                        return;
                    } else {
                        let _table = _dom.querySelector('table.rx-table');
                        if (!_table){
                            continue
                        }
                        let _tBody = _table.querySelector('tbody');
                        let _tr = _tBody.querySelectorAll('tr');
                        if (!_tBody || _tr){
                            continue
                        }
                        for (let n = 0; n < _tr.length; n++) {
                            let _td = _tr[n].querySelectorAll('td');
                            for (let m = 0; m < _td.length; m++) {
                                let _getTabName = _td[m].querySelector('[tabname]');
                                if (!_getTabName) {
                                    continue;
                                }
                                let _clas = _getTabName.getAttribute('class');
                                let _tabName = _getTabName.getAttribute('tabname');
                                let _inputVal = this.tableValidation(_getTabName);
                                let row = n + 1;
                                if (_clas.includes('rx-switch') && !_inputVal) {
                                    MessageBox.show({
                                        message: this.i18n('form.table','子表的第')+"【" + row + this.i18n('form.line','】行，第【') + _tabName + "】"+i18n('form.fields','列是必填项'),
                                        data: ''
                                    })
                                    return;
                                } else if (_clas.includes('requireds') && !_inputVal) {
                                    MessageBox.show({
                                        message: this.i18n('form.table','子表的第')+"【" + row + this.i18n('form.line','】行，第【') + _tabName + "】"+i18n('form.fields','列是必填项'),
                                        data: ''
                                    })
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            this.fromTabActive = 'tab' + _i;
        },
        getElm(node, em, all) {
            let _elms = '', _nodes = node, _em = em;
            if (all) {
                _elms = _nodes.querySelectorAll(_em);
            } else {
                _elms = _nodes.querySelector(_em);
            }
            return _elms;
        },
        tableValidation(node) {
            var _self = this;
            var _node = node;
            var _inputVal = ''
            var _ctltype = _node.getAttribute('ctltype');

            //type:节点的ctltype；
            //em:需要获取的dom节点；
            //all获取的方式，all="false" querySelector 或者all="true" querySelectorAll;
            //fn判断方式；1.直接判断节点node；2.判断节点的length长度len,3.取反no,4.其它情况other
            //value:返回取值，value:'val'返回值，value:'blen'返回布尔值；

            let obj = [
                {type: 'rx-textbox', em: 'input', all: false, fn: 'node', value: 'val'},
                {type: 'rx-number', em: 'input', all: false, fn: 'node', value: 'val'},
                {type: 'rx-date', em: 'input', all: false, fn: 'node', value: 'val'},
                {type: 'rx-month', em: 'input', all: false, fn: 'node', value: 'val'},
                {type: 'rx-week', em: 'input', all: false, fn: 'node', value: 'val'},
                {type: 'rx-time', em: 'input', all: false, fn: 'node', value: 'val'},
                {type: 'rx-date-range', em: 'input', all: true, fn: 'len', value: 'val'},
                {type: 'rx-textarea', em: 'textarea', all: false, fn: 'node', value: 'val'},
                {type: 'rx-checkbox-list', em: '.ant-checkbox-wrapper-checked', all: true, fn: 'len', value: 'blen'},
                {type: 'rx-radio', em: '.ant-radio-wrapper-checked', all: false, fn: 'node', value: 'blen'},
                {type: 'rx-switch', em: '.ant-switch-checked', all: false, fn: 'node', value: 'blen'},
                {
                    type: 'rx-form-select',
                    em: '.ant-select-selection-selected-value',
                    all: false,
                    fn: 'other',
                    value: 'blen'
                },
                {type: 'rx-group', em: '.item-list-tag', all: true, fn: 'len', value: 'blen'},
                {type: 'rx-user', em: '.item-list-tag', all: true, fn: 'len', value: 'blen'},
                {type: 'rx-map', em: '.item-list-tag', all: true, fn: 'len', value: 'blen'},
                {type: 'rx-quill-editor', em: '.ql-blank', all: false, fn: 'no', value: 'blen'},
                {type: 'rx-upload', em: '.upBox', all: true, fn: 'len', value: 'blen'},
                {type: 'rx-address', em: '.ant-select-selection-selected-value', all: false, fn: 'node', value: 'blen'},
                {type: 'rx-rate', em: 'ul.ant-rate', all: false, fn: 'other', value: 'blen'},
                {type: 'rx-button-edit', em: '.rx-inputs.ant-input', all: false, fn: 'node', value: 'val'}
            ]

            for (let i = 0; i < obj.length; i++) {
                let _type = obj[i].type;
                let _em = obj[i].em;
                let _all = obj[i].all;
                let _fn = obj[i].fn;
                let _vlaue = obj[i].value || '';
                if (_ctltype == _type) {
                    let _elmt = _self.getElm(_node, _em, _all);
                    //判断方式；1.直接判断节点node；2.判断节点的length长度len,3.取反no,4.其它情况other
                    if (_fn == 'node') {
                        if (_elmt) {
                            if (_vlaue == 'val') {
                                _inputVal = _elmt.value
                            }
                            if (_vlaue == 'blen') {
                                _inputVal = true;
                            }
                        }
                    }
                    if (_fn == 'len') {
                        if (_elmt.length) {
                            if (_vlaue == 'val') {
                                //rx-date-range是根据length判断的，所以只在这里判断了一下；
                                if (_type == 'rx-date-range') {
                                    _inputVal = _elmt[0].value
                                } else {
                                    _inputVal = _elmt.value
                                }
                            }
                            if (_vlaue == 'blen') {
                                _inputVal = true;
                            }
                        }
                    }
                    if (_fn == 'no') {
                        if (!_elmt) {
                            //取反情况下只有一个：rx-quill-editor 所以里面就不做其它判断了；
                            _inputVal = true;
                        }
                    }
                    if (_fn == 'other') {
                        if (_type == 'rx-form-select') {
                            let _title = _elmt.getAttribute('title');
                            if (_elmt && _title) {
                                _inputVal = true;
                            }
                        }
                        if (_type == 'rx-rate') {
                            let _antStar = _elmt.querySelectorAll('.ant-rate-star');
                            let _star = _antStar[0].querySelector('div[role="radio"]').getAttribute('aria-checked');
                            if (JSON.parse(_star)) {
                                _inputVal = true;
                            }
                        }

                    }
                }
            }
            return _inputVal;

        },
        delayCalc: debounce(function (newValue, self_) {
            FormCalc.calc(self_.formula, newValue);
            FormCalc.calcAreas(self_.calcAreas, newValue, self_);
        }, 500),
        getRead(read) {
            return this.readonly ? this.readonly : read;
        },
        blockSelect(str,blockStr){//块选择显示隐藏
            //str塊選擇控件的 字段標識 ；
            //blockStr選中的key值；
            let _data = this.data[str];
            if(_data){
                let _active = JSON.parse(_data).activeTable;
                return blockStr == _active ? true :false ;
            }
        },
        getSubTableField(self,name,id){
            //根據子表標識鍵name,或者子表的id得到子表的 所有字段;
            let _fields = '';
            if(id){
                _fields = self.metadata[id];
            }else {
                let _meta = self.metadata ;
                for(let key in _meta){
                    let _field = _meta[key];
                    if(_field.name == name){
                        _fields = _field ;
                    }
                }
            }
            return _fields
        },
        setField(self,filedName,key,val){
            // self 當前form的实例(this);
            //filedName需要修改的控件的 字段标识，
            //key 需要修改的key
            //val 修改的值 ；
            let _subTable = '';
            let _meta = self.metadata ;
            for(let key in _meta){
                let _field = _meta[key];
                if(_field.name == fieldName){
                    _subTable = _field ;
                    break ;
                }
            }
            _subTable[key] = val ;
        },
        setSubTableField(self,tableName,filedName,key,val,){
            //self 當前form的this ;
            //tableName當前子表的字段標識；
            // field是否是修改子表fields數組裏面的字段；
            //filedName： 則需要指定修改控件的字段標識 ;
            // key需要修改值的對應的key；
            // val修改的值；
            let _subTable = '';
            let _meta = self.metadata ;
            for(let key in _meta){
                let _field = _meta[key];
                if(_field.name == tableName){
                    _subTable = _field ;
                    break ;
                }
            }
            let _data = _subTable['fields'] ;
            for(let item of _data){
                let _name = item['name'] ;
                if (_name == filedName){
                    item[key] = val ;
                }
            }
        },
        cancel(){
            Util.closeWindow(this,"cancel");
        },
        /**
         * 保存数据。
         * @param Api
         */
        async handSubmit(Api, vm) {
            let self_=this;
            if (this._beforeSubmit) {
                var rtn = await self_._beforeSubmit();
                if (rtn && !rtn.success) {
                    self_.$message.warn(rtn.msg);
                    vm.loading = false;
                    return;
                }
            }
            Api.saveData(self_.data).then(res => {
                Util.closeWindow(self_, "ok",self_.data);
            })
        },

        loadData(Api){
            let self_=this;
            //加载表单数据
            var pk=self_.pkId || "";
            Api.getById(pk).then(res=>{
                self_.data=res;
                self_.iscompleteMain=true;
                //self_.onload();
                self_.initDataFun("getById");
                //获取左树右列表选择树信息
                self_.getCurTree();
            })
        }


    },
    watch: {
        //观察数据变化。
        data: {
            handler: function (newValue, oldValue) {
                this.delayCalc(newValue, this);
            },
            deep: true
        },
        item: {
            handler: function (newValue, oldValue) {
                //执行子表弹出的表单公式
                var aryData=FormCalc.handData(this.data.data);
                for(var rowField in this.formula[this.subName]) {
                    var formula = this.formula[this.subName][rowField];
                    formula = FormCalc.handRowFormula(formula, aryData).formula;
                    var row = newValue;
                    var val = eval(formula);
                    row[rowField] = val;

                }
            },
            deep: true
        }
    }
}

